function identify(value) {
  return value
}

// high-order reducers
function handleAction(actionType, reducer = identify, defaultReducer) {
  return (state, action) => {
    const { type } = action
    if (type && actionType !== type) {
      return defaultReducer(state, action)
    }
    return reducer(state, action)
  }
}

function reduceReducers(...reducers) {
  return (previous, current) =>
    reducers.reduce((p, r) => r(p, current), previous)
}

function handleActions(handlers, defaultState, defaultHandler = identify) {
  const reducers = Object.keys(handlers).map(type =>
    handleAction(type, handlers[type], defaultHandler),
  )
  const reducer = reduceReducers(...reducers)
  return (state = defaultState, action) => reducer(state, action)
}

export default handleActions
